//线程的状态
/*
 * 1. NEW: 线程刚创建，还没有调用start()方法。
 * 2. RUNNABLE: 线程正在执行，或者在等待CPU调度。
 * 3. BLOCKED: 线程被阻塞，等待其他线程释放锁。
 * 4. WAITING: 线程等待其他线程通知。
 * 5. TIMED_WAITING: 线程等待其他线程通知，但是有时间限制。
 * 6. TERMINATED: 线程执行完毕。
 */

public class Test_3 {
    public static void main(String[] args) {
        //demo1();
        // demo2();
        demo3();
    }

    //观察 NEW 、RUNNABLE、TERMINATED的状态转换
    public static void demo1() {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // 这里可以添加具体逻辑
            }
        }, "李四");

        System.out.println(t.getName() + ": " + t.getState());
        t.start();

        while (t.isAlive()) {
            System.out.println(t.getName() + ": " + t.getState());
        }

        System.out.println(t.getName() + ": " + t.getState());
    }

    //观察 RUNNABLE、BLOCKED、TIMED_WAITING的状态转换
    public static void demo2() {
        final Object object = new Object();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "t1");
        t1.start();
        System.out.println(t1.getName()+  ": " + t1.getState());
        
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    System.out.println("hehe");
                }
            }
        }, "t2");
        t2.start();
        System.out.println(t1.getName() + ": " + t1.getState());
        System.out.println(t2.getName() + ": " + t2.getState());
    }

    //将demo2中的 sleep 改为 wait 观察状态的转换
    public static void demo3() {
        final Object object = new Object();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1");
        t1.start();
        System.out.println(t1.getName()+  ": " + t1.getState());
        
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    System.out.println("hehe");
                }
            }
        }, "t2");
        t2.start();
        System.out.println(t1.getName() + ": " + t1.getState());
        System.out.println(t2.getName() + ": " + t2.getState());
    }
}
